package com.leyou.cart.interceptor;

import com.leyou.auth.pojo.Payload;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.utils.CookieUtils;
import com.netflix.discovery.converters.Auto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Rose
 * @Date: 2021/4/11 19:09
 * @description ${description}
 * @version: 1.0.0
 */
@Component
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    public static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取Cookie 中的token信息
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        try {
            // 解析token
            Payload<UserInfo> fromToken = JwtUtils.getInfoFromToken(token, jwtProperties.getPubKey(), UserInfo.class);
            UserInfo userInfo = fromToken.getUserInfo();
            // 传递user
            //request.setAttribute("user", userInfo);
            tl.set(userInfo);

            // 放行
            return true;
        } catch (Exception e) {
            log.error("[购物车服务] 解析用户身份失败. 失败原因：{}", e.getMessage());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 最后用完数据，一定要清空
        tl.remove();
    }

    public static UserInfo getUserInfos() {
        return tl.get();
    }
}
